/*
 * @author Rahat Ahmed
 * 
 * @description Searches the logs for a regex pattern.
 * 
 * @basecmd grep
 * 
 * @category utility
 */package commands;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.pircbotx.Channel;
import org.pircbotx.User;

import cmods.LoggingCModule.EventType;

import backend.Bot;
import backend.Database;
import backend.Util;

public class GrepCommand extends Command
{
	public static final int PASTEBIN_LIMIT = 5;
	private static final SimpleDateFormat timestampFormat = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");

	@Override
	protected void initialize()
	{
		setName("GrepCommand");
		addAlias("grep");
		setHelpText("Searches the logs for a regex pattern.");
	}
	
	@Override
	public void execute(Bot bot, Channel chan, User user, String message)
	{
		if(Util.hasArgs(message, 2))
		{
			try
			{
				String[] cmd = Util.getArgs(message, 2);
				String[] results = grep(chan.getName(), cmd[1]);
				System.out.println(results[0]);
				if(results.length == 1 && results[0] == null)
				{
					passMessage(bot, chan, user, "No results found.");
				}
				else if(results.length <= PASTEBIN_LIMIT)
				{
					for(String s:results)
						if(s!=null)
							bot.sendMessage(user, s);
				}
				else
				{
					StringBuilder text = new StringBuilder();
					for(String s:results)
						if(s!=null)
							text.append(s);
					passMessage(bot, chan, user, Util.pastebin(text.toString()));
				}
			
			} catch (SQLException e) {
				passMessage(bot, chan, user, "bluh bluh Freek sucks at SQL!");
				e.printStackTrace();
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	public String[] grep(String chan, String pattern) throws SQLException, ParseException
	{
		List<HashMap<String, Object>> query = Database.select("SELECT * FROM LoggingCModule_logs WHERE CHANNEL="+Database.getEnclosedString(chan)+" and MESSAGE REGEXP "+Database.getEnclosedString(".*"+pattern+".*")+"  ORDER BY id DESC");
		StringBuffer backlog = new StringBuffer();
		String[] log = new String[query.size()];
		int pos = 0;
		for(int k=query.size()-1;k>=1;k--)
		{
			HashMap<String, Object> row = query.get(k);
			backlog.append("[");
			backlog.append(timestampFormat.format(new Date(((Timestamp) row.get("TIME")).getTime())));
			backlog.append("] ");
			if(((Short)row.get("EVENT_TYPE")) == EventType.MESSAGE.ordinal())
			{
				backlog.append("<");
				backlog.append(((String) row.get("USER_NAME")).trim());
				backlog.append("> ");
			}
			backlog.append(((String) row.get("MESSAGE")).trim());
			backlog.append("\n");
			log[pos++] = backlog.toString();
			backlog = new StringBuffer();
		}
		return log;
	}

}
